

#import "NetWorkingManager.h"
#import <AFNetworking.h>
#import "NSObject+additions.h"
#import "NSString+additions.h"
#import "ZJAdditions.h"
#define DreamSoft @"dreamsoft"

@implementation NetWorkingManager
+ (void)postWithUrlString:(NSString *)url Parameter:(NSDictionary *)parameter Success:(NetBlock)successBlock Fail:(NetBlock)failBlock{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置网络请求超时时间
    manager.requestSerializer.timeoutInterval = 30.f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",nil];
   manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
    NSString *SYS_ACCOUNTID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.ID :@"";
    NSString *SYS_PARTYMEMBERID = ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID : @"";
    NSString *string;
    if (parameter) {
        NSMutableDictionary *dict = [parameter mutableCopy];
        [dict setObject:SYS_ACCOUNTID forKey:@"SYS_ACCOUNTID"];
        [dict setObject:SYS_PARTYMEMBERID forKey:@"SYS_PARTYMEMBERID"];
        [dict setValue:[ToolClass getMacAddress] forKey:@"SYS_MAC"];
        string = [self jsonStringFromObject:dict];
    }else{
        NSString * tempString = [ToolClass getMacAddress];
        if (tempString.length == 0) {
            tempString = @"";
        }
        string = [self jsonStringFromObject:@{@"SYS_ACCOUNTID":SYS_ACCOUNTID,
                                              @"SYS_PARTYMEMBERID":SYS_PARTYMEMBERID,
                                              @"SYS_MAC":tempString}];
    }
    NSString *string1 =  [NSString stringWithFormat:@"<Request  action='%@' request='JSON' response='JSON' nohead='true'><Data>%@</Data></Request>",url,string];

    NSData *data = [string1 dataUsingEncoding:NSUTF8StringEncoding];
    //base64加密编码
    NSString *stringBase64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSDictionary *pargem = @{DreamSoft:stringBase64};
    __weak typeof(self) weakSelf = self;
    [manager POST:BASEURL parameters:pargem progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * responseString = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [weakSelf jsonStringToObject:responseString];
        
        successBlock(dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    
        failBlock(error);
        
    }];
}



+ (void)ybPostWithUrlString:(NSString *)url Parameter:(NSDictionary *)parameter getTask:(void (^)(NSURLSessionDataTask *))getTask Success:(NetBlock)successBlock Fail:(NetBlock)failBlock{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置网络请求超时时间
    manager.requestSerializer.timeoutInterval = 30.f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",nil];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",nil];
    NSString *SYS_ACCOUNTID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.ID :@"";
    NSString *SYS_PARTYMEMBERID = ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID : @"";
    NSString *string;
    if (parameter) {
        NSMutableDictionary *dict = [parameter mutableCopy];
        [dict setObject:SYS_ACCOUNTID forKey:@"SYS_ACCOUNTID"];
        [dict setObject:SYS_PARTYMEMBERID forKey:@"SYS_PARTYMEMBERID"];
        string = [self jsonStringFromObject:dict];
    }else{
        string = [self jsonStringFromObject:@{@"SYS_ACCOUNTID":SYS_ACCOUNTID,
                                              @"SYS_PARTYMEMBERID":SYS_PARTYMEMBERID}];
    }
    NSString *string1 =  [NSString stringWithFormat:@"<Request  action='%@' request='JSON' response='JSON' nohead='true'><Data>%@</Data></Request>",url,string];
    
    NSData *data = [string1 dataUsingEncoding:NSUTF8StringEncoding];
    //base64加密编码
    NSString *stringBase64 = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    
    NSDictionary *pargem = @{DreamSoft:stringBase64};
    __weak typeof(self) weakSelf = self;
     NSURLSessionDataTask * ybTask = [manager POST:BASEURL parameters:pargem progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString * responseString = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [weakSelf jsonStringToObject:responseString];
        successBlock(dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failBlock(error);
        
    }];
    if (getTask) {
        getTask(ybTask);
    }
}


+ (void)uploadingWithXMLString:(NSString *)xmlString
                     Parameter:(NetWorkUpLoadModel *)parameter
                       Success:(NetBlock)successBlock
                          Fail:(NetBlock)failBlock{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",@"text/javascript",@"text/plain", nil];
    
    //1、把文件对象数组转化成数组
    NSArray *fileArray = [parameter.UPLOAD_FILES yy_modelToJSONObject];
    //2、除去data，得到数组
    __block NSMutableArray *nofileDataArray = [NSMutableArray array];//保存新数组
    
    NSMutableDictionary *netWorkUpLoadModel = [[parameter yy_modelToJSONObject] mutableCopy];
    NSString *SYS_ACCOUNTID = ZJUSERINFORMODEL.ORG_ACCOUNT.ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.ID :@"";
    NSString *SYS_PARTYMEMBERID = ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID ? ZJUSERINFORMODEL.ORG_ACCOUNT.PARTY_MEMBER_ID : @"";
    [netWorkUpLoadModel setObject:SYS_ACCOUNTID forKey:@"SYS_ACCOUNTID"];
    [netWorkUpLoadModel setObject:SYS_PARTYMEMBERID forKey:@"SYS_PARTYMEMBERID"];
    [fileArray enumerateObjectsUsingBlock:^(NSMutableDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeObjectForKey:@"fileUrl"];
        [nofileDataArray addObject:obj];
    }];
    
    NSString * dateString = [NSString stringWithFormat:@"FILES_%@_KEYS",[NSString getCurrentDate]];
    
    [manager POST:UPLOADURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [netWorkUpLoadModel.allKeys enumerateObjectsUsingBlock:^(NSString *  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
            //不为fileArray 且有值时
            if (![key isEqualToString:@"UPLOAD_FILES"] && [netWorkUpLoadModel objectForKey:key]) {
                [formData appendPartWithFormData:[netWorkUpLoadModel[key] dataUsingEncoding:NSUTF8StringEncoding] name:key];
            }
        }];
        
        [parameter.UPLOAD_FILES enumerateObjectsUsingBlock:^(NetWorkUploadFileModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (obj.FILE_PATH) {
                NSData  *fileData= obj.FILE_PATH;//二进制数据
                NSString *mimeType= @".jpg";//文件类型
                NSString *oldFileNameLast=[obj.FILE_NAME lastPathComponent];//文件原来的名字
                //取文件名的后缀
                NSString *fileNameLast = [oldFileNameLast zj_subStringLastOfString:@"."];
                //拼接最新的文件名
                NSString *fileName = [NSString stringWithFormat:@"%ld%@",(unsigned long)idx,fileNameLast];
                [formData appendPartWithFileData:fileData name: [NSString stringWithFormat:@"%lu",(unsigned long)idx] fileName:fileName mimeType:mimeType];
            }
        }];
        
        [formData appendPartWithFormData:[nofileDataArray yy_modelToJSONData] name:dateString];
        [formData appendPartWithFormData:[xmlString dataUsingEncoding:NSUTF8StringEncoding] name:@"ACTION_XML"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //成功
        successBlock(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //失败
        failBlock(error);
    }];
}


#pragma mark - 下载
+ (void)downLoadWithUrlString:(NSString *)UrlString success:(void(^)(NSURL *localUrlString))success
{
    //1.创建会话管理者
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    
    NSURL *url = [NSURL URLWithString:UrlString];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *download = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        
        //监听下载进度
        //completedUnitCount 已经下载的数据大小
        //totalUnitCount     文件数据的中大小
//        CGFloat progress = 1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        /**
         * 1:1：请求路径：NSUrl *url = [NSUrl urlWithString:path];从网络请求路径  2：把本地的file文件路径转成url，NSUrl *url = [NSURL fileURLWithPath:fullPath]；
         2：返回值是一个下载文件的路径
         *
         */
        NSArray *array =  [response.suggestedFilename componentsSeparatedByString:@"."];
        NSString *name = [NSString stringWithFormat:@"%@.caf",array[0]];
        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:name];
        
        return [NSURL fileURLWithPath:fullPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        /**
         *filePath:下载后文件的保存路径
         */
        if (success) {
            success(filePath);
        }
    }];
    //3.执行Task
    [download resume];
}



///appUpdate
+ (void)appUpdate_Success:(NetBlock)successBlock
                     Fail:(NetBlock)failBlock{
    __weak typeof(self) weakSelf = self;
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //设置网络请求超时时间
    manager.requestSerializer.timeoutInterval = 30.f;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/JavaScript",@"text/html",nil];
    
    [manager GET:APPUPDATEURL parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSString * responseString = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
        NSDictionary *dict = [weakSelf jsonStringToObject:responseString];
        
        successBlock(dict);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        failBlock(error);
    }];
}


//获取文件类型
+ (NSString*)getMIMEType:(NSString *)path

{
    NSError *error;
    NSURLResponse*response;
    NSURLRequest*request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [NSURLConnection sendSynchronousRequest:request
                          returningResponse:&response
                                      error:&error];
    return [response MIMEType];
}

@end
